/**
 * v-swipe: function 如果向上滚动返回 'up' 如果向下滚动返回 'down'
 * swipe-distance: 滚动的有效距离, 如果未达到有效距离不算滚动
 */

let glob = {
	el: '',
	binding: '',
	distance: 0
};

let touchStart = (event) => {
	let target = event.target;
	target['oldScreenY'] = event.targetTouches[0].screenY;
	target['oldScreenX'] = event.targetTouches[0].screenX;
};

let touchMove = (event) => {
	let target = event.target;
	target['newScreenY'] = event.targetTouches[0].screenY;
	target['newScreenX'] = event.targetTouches[0].screenX;

	let lastDistanceY = target['oldScreenY'];
	let curDistanceY = target['newScreenY'];
	let lastDistanceX = target['oldScreenX'];
	let curDistanceX = target['newScreenX'];

	// console.log(`cur_distance: ${target['newScreen']} --- last_distance: ${target['oldScreen']}`);

	let distanceX = curDistanceX - lastDistanceX;
	let distanceY = curDistanceY - lastDistanceY;

	if (Math.abs(distanceX) > Math.abs(distanceY)) {
		if (distanceX > 0 && distanceX > glob.distance) {
			glob.binding.value({ direction: 'left', distance: distanceX });
		}
		else if (distanceX < 0 && distanceX < glob.distance) {
			glob.binding.value({ direction: 'right', distance: distanceX });
		}
	}
	else {
		if (distanceY > 0 && distanceY > glob.distance) {
			glob.binding.value({ direction: 'up', distance: distanceY });
		}
		else if (distanceY < 0 && distanceY < glob.distance) {
			glob.binding.value({ direction: 'down', distance: distanceY });
		}
	}
};

export default {
	bind (el, binding, vnode) {
		glob.el = el;
		glob.binding = binding;

		glob.distance = el.getAttribute('swipe-distance') ? el.getAttribute('swipe-distance') : 0;

		el.addEventListener('touchstart', touchStart);
		el.addEventListener('touchmove', touchMove);
	},
	unbind (el) {
		el.removeEventListener('touchstart', touchStart);
		el.removeEventListener('touchmove', touchMove);
	}
};
